package com.sensetime.jv.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.sensetime.jv.service.CaptchaService;
import com.sensetime.jv.util.RedisCache;
import com.sensetime.jv.vo.response.CaptchaVO;
import io.netty.util.internal.StringUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@AllArgsConstructor
public class CaptchaServiceImpl implements CaptchaService {


    private final RedisCache redisCache;

    private static final String CAPTCHA_PREFIX = "custom:captcha:";
    private static final long EXPIRE_SECONDS   = 3 * 60; // 3 分钟

    /**
     * 生成验证码
     */
    @Override
    public String generate(String bizType, String target) {
        String key = CAPTCHA_PREFIX + bizType + ":" + target;
        // 生成 4 位图形验证码
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(120, 40, 4, 10);
        String code = captcha.getCode();
        // 保存到 Redis，3 分钟过期
        log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<验证码：{}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<",code);
        redisCache.setCacheObject(key, code, (int) EXPIRE_SECONDS, TimeUnit.SECONDS);
        // 返回给前端
        return captcha.getImageBase64Data();
    }

    /**
     * 验证验证码
     * 成功：返回 true
     * 失败：删除旧验证码 + 重新生成 + 返回 false
     */
    @Override
    public boolean validate(String bizType, String target, String inputCode) {
        if (StringUtil.isNullOrEmpty(inputCode)){
            return false;
        }
        String key = CAPTCHA_PREFIX + bizType + ":" + target;
        String cacheCode = redisCache.getCacheObject(key);
        if (cacheCode == null) {
            // 已过期
            return false;
        }
        boolean ok = cacheCode.equalsIgnoreCase(inputCode.trim());
        if (ok) {
            redisCache.deleteObject(key); // 验证通过立即删除
        } else {
            redisCache.deleteObject(key); // 验证失败也删除，强制重新生成
        }
        return ok;
    }

}
